package com.tiancikeji.zaoke.app.biz.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import com.tiancikeji.zaoke.app.biz.ZoneBiz;
import com.tiancikeji.zaoke.app.comparator.ZoneComparator;
import com.tiancikeji.zaoke.app.model.zone.Zone;
import com.tiancikeji.zaoke.app.service.zone.ZoneService;

public class ZoneBizImpl implements ZoneBiz {

	private ZoneService zoneService;
	
	public Zone getZoneById(long zoneId) {
		Zone zone = zoneService.getZoneById(zoneId);
		
		if(zone != null && zone.getState() == Zone.STATE_ACTIVE && zone.getType() == Zone.TYPE_PICK && StringUtils.isNotBlank(zone.getName())
				&& StringUtils.isNotBlank(zone.getPickStartTime()) && StringUtils.isNotBlank(zone.getPickEndTime()))
			return zone;
		else
			return null;
	}

	public List<Zone> getZones() {
		Set<Zone> result = new HashSet<Zone>();
		Set<Zone> zones = zoneService.getAllZones();
		
		List<Zone> tails = new ArrayList<Zone>();
		Map<Long, Zone> zonesMap = new HashMap<Long, Zone>();
		if(zones != null && zones.size() > 0)
			for(Zone zone : zones)
				if(zone.getType() == Zone.TYPE_PICK)
					tails.add(zone);
				else
					zonesMap.put(zone.getId(), zone);
		
		if(tails.size() > 0)
			for(Zone tail : tails){
				while(tail != null && tail.getParentId() > 0 && zonesMap.containsKey(tail.getParentId())){
					Zone tmp = zonesMap.get(tail.getParentId());
					List<Zone> subZones = tmp.getSubZones();
					if(subZones == null){
						subZones = new ArrayList<Zone>();
						tmp.setSubZones(subZones);
					}
					if(!tail.isFlag()){
						subZones.add(tail);
						tail.setFlag(true);
					}
					tail = tmp;
				}
				
				if(tail.getType() == Zone.TYPE_DISTRICT && !tail.isFlag()){
					result.add(tail);
					tail.setFlag(true);
				}
			}
		
		if(result != null && result.size() > 0){
			List<Zone> resList = new ArrayList<Zone>(result);
			ZoneComparator zc = new ZoneComparator();
			_sort(resList, zc);
			return resList;
		}
		
		return null;
	}
	
	private void _sort(List<Zone> zones, ZoneComparator zc) {
		if(zones != null && zones.size() > 0){
			Collections.sort(zones, zc);
			for(Zone zone : zones)
				if(zone != null && zone.getSubZones() != null && zone.getSubZones().size() > 0)
					_sort(zone.getSubZones(), zc);
		}
	}

	public ZoneService getZoneService() {
		return zoneService;
	}

	public void setZoneService(ZoneService zoneService) {
		this.zoneService = zoneService;
	}
}
